// #include <windows.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>

int width, height;

void MyCircle(int xc, int yc, int r) {
// (xc, yc)	--- Center coordinates
// r --- Radius
	int x, y, p;
	x=0;
	y=r;
	p = 5.0/4 - r;
	glBegin(GL_POINTS);
	while(x < y) {
		glVertex2i(xc+x, yc+y);
		glVertex2i(xc+x, yc-y);
		glVertex2i(xc-x, yc+y);
		glVertex2i(xc-x, yc-y);
		glVertex2i(xc+y, yc+x);
		glVertex2i(xc+y, yc-x);
		glVertex2i(xc-y, yc+x);
		glVertex2i(xc-y, yc-x);

		x = x + 1;
		if(p < 0)
			p += 2*x + 1;
		else {
			y -= 1;
			p += 2*x - 2*y + 1;
		}
	}
	glEnd();
}

void MyEllipse(int xc, int yc, int rx, int ry) {
	// (xc, yc) --- Center coordinates
	// rx --- Radius in x direction
	// ry --- Radius in y direction
	int x, y, p;
	x = 0;
	y = ry;
	p = ry*ry - rx*rx*ry + 0.25*rx*rx;
	glBegin(GL_POINTS);
	while(ry*ry*x < rx*rx*y) {
		glVertex2i(xc+x, yc+y);
		glVertex2i(xc+x, yc-y);
		glVertex2i(xc-x, yc+y);
		glVertex2i(xc-x, yc-y);

		x += 1;
		if(p < 0)
			p += pow(ry, 2)*(2*x+1);
		else {
			y -= 1;
			p += pow(ry, 2)*(2*x+1) - 2*pow(rx, 2)*y;
		}
	}

	p = pow(ry, 2)*pow(x+0.5, 2) + pow(rx, 2)*pow(y-1, 2) - pow(rx*ry, 2);
	while(y >= 0) {
		glVertex2i(xc+x, yc+y);
		glVertex2i(xc+x, yc-y);
		glVertex2i(xc-x, yc+y);
		glVertex2i(xc-x, yc-y);

		y -= 1;
		if(p > 0)
			p += pow(rx, 2)*(-2*y+1);
		else {
			x += 1;
			p += pow(rx, 2)*(-2*y+1) + 2*pow(ry, 2)*x;
		}
	}
	glEnd();

}

void reshape(int w, int h) {
	width = w;
	height = h;

	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, w, 0.0, h);
}

void keyboard(unsigned char key, int x, int y) {
	switch(key) {
		case 27:
			exit(0);
	}
}

void display(void) {
	
	glClear(GL_COLOR_BUFFER_BIT);

	glColor3f(1.0, 0.0, 0.0);
	MyCircle(150, 150, 100);
	glColor3f(1.0, 0.0, 1.0);
	MyCircle(150, 150, 60);

	glColor3f(1.0, 1.0, 1.0);
	MyEllipse(150, 350, 131, 50);
	MyEllipse(400, 350, 29, 89);

	glFlush();
}

int main(int argc, char * argv[]) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
	glutInitWindowPosition(500, 500);
	glutInitWindowSize(500, 500);
	glutCreateWindow("Circles and Ellipses");

	//
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);

	glutDisplayFunc(display);

	glutMainLoop();

	return 0;
}
